import {
	setStore,
	getStore,
	clearUserSeesion,
	setToken,
	getRToken
} from '@/util/store'
import {
	isURL,
	validatenull
} from '@/util/validate'
import {
	deepClone
} from '@/util/util'
import {
	ReviewedGoodsNum
} from '@/api/base/goods/goodsApprove';
import {auditAdvertNumber} from "@/api/base/operations/advertManage/advert"

import webiste from '@/config/website'
import {
	loginByUsername,
	getUserInfo,
	getMenu,
	getTopMenu,
	logout,
	refeshToken,
	idmAutho2Login
} from '@/api/user'
import constants from "@/const/constants";

function addPath(ele, first) {
	const menu = webiste.menu;
	const propsConfig = menu.props;
	const propsDefault = {
		label: propsConfig.label || 'label',
		path: propsConfig.path || 'path',
		icon: propsConfig.icon || 'icon',
		children: propsConfig.children || 'children'
	}
	const icon = ele[propsDefault.icon];
	ele[propsDefault.children] = ele[propsDefault.children] || [];
	ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
	const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
	if (!isChild && first && !isURL(ele[propsDefault.path])) {
		ele[propsDefault.path] = ele[propsDefault.path] + '/index'
	} else {
		ele[propsDefault.children].forEach(child => {
			if (!isURL(child[propsDefault.path])) {
				child[propsDefault.path] =
					`${ele[propsDefault.path]}/${child[propsDefault.path] ? child[propsDefault.path] : 'index'}`
			}
			addPath(child);
		})
	}
}
const user = {
	state: {
		userInfo: {},
		permission: {},
		roles: [],
		tokenLock: false,
		reviewNum: 0,
		advertNum:0,
		menu: getStore({
			name: 'menu'
		}) || [],
		menuAll: [],
		token: getStore({
			name: 'token'
		}) || '',
		msgdict: {}
	},
	actions: {
		//根据用户名登录
		LoginByUsername({
			commit
		}, user) {
			return new Promise((resolve, reject) => {
				loginByUsername(user.username, user.password).then(res => {
					const data = res.data.data;
					setStore({
						name: 'isNeedModifyPassword',
						content: data.isNeedModifyPassword
					});
					commit('SET_TOKEN', data); //设置token   方法中实现将token加入在session中
					commit('DEL_ALL_TAG');
					commit('OPEN_LOCK'); //将锁打开
					resolve(res);
				}).catch(err => {
					reject(err)
				})
			})
		},
		//根据手机号登录
		LoginByPhone({
			commit
		}, userInfo) {
			return new Promise((resolve) => {
				loginByUsername(userInfo.phone, userInfo.code).then(res => {
					const data = res.data.data;
					commit('SET_TOKEN', data);
					commit('DEL_ALL_TAG');
					commit('CLEAR_LOCK');
					resolve();
				})
			})
		},
		GetUserInfo({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getUserInfo().then((res) => {
					const data = res.data.data;
					commit('SET_USERIFNO', data);
					commit('SET_ROLES', data.roleIds);
					commit('SET_PERMISSION', data.permissions);
					resolve(data);
				}).catch(err => {
					reject(err);
				})
			})
		},
		//刷新token
		RefeshToken({
			state,
			commit
		}) {
			return new Promise((resolve, reject) => {
				var rToken = getRToken();
				console.log(rToken);
				refeshToken(rToken).then(res => {
					const data = res.data.data;
					commit('SET_TOKEN', data);
					resolve(data);
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登出
		LogOut({
			commit
		},logoutHref) {
			return new Promise((resolve, reject) => {
				logout().then(res => {
					commit('SET_TOKEN', '')
					commit('SET_MENU', [])
					commit('SET_ROLES', [])
					commit('DEL_ALL_TAG');
					commit('CLEAR_LOCK');
					//清空sessionstore
					clearUserSeesion();
					//关闭socket
					if (constants.SOCKET) {
						if (constants.SOCKET.readyState == 2) {
							constants.SOCKET.close();
						}
					}
					console.log('href'+res.data.data)
					if(res.data.data != ''){
						window.location.href = res.data.data;
					}else{
						// window.location.reload();
						window.location.href = logoutHref;
					}
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		//跳转idm登录地址
		getLoginUrl() {
			return new Promise((resolve, reject) => {
				idmAutho2Login().then(res => {
					window.location.href = res.data.data.url;
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		//获取code登录
		getCodeLogin({
			 commit
		},codeData) {
			return new Promise((resolve, reject) => {
				idmAutho2Login(codeData.code).then(res => {
					if(res.data.code == 200){
						const data = res.data.data;
						commit('SET_TOKEN', data);
						commit('DEL_ALL_TAG');
						commit('CLEAR_LOCK');
						window.location.href = codeData.href+'?white=true';
					}else{
						localStorage.setItem('errorMsgYc', res.data.message);
						window.location.href = codeData.href+'?rcLogin=0';
					}
					resolve();
				}).catch(error => {
					reject(error)
				})
			})
		},
		//注销session
		FedLogOut({
			commit
		}) {
			return new Promise(resolve => {
				commit('SET_TOKEN', '')
				commit('SET_MENU', [])
				commit('SET_ROLES', [])
				commit('DEL_ALL_TAG');
				commit('CLEAR_LOCK');
				//清空sessionstore
				clearUserSeesion();
				//关闭socket
				if (constants.SOCKET) {
					constants.SOCKET.close();
				}
				window.location.reload();
				resolve()
			})
		},
		GetTopMenu() {
			return new Promise(resolve => {
				getTopMenu().then((res) => {
					const data = res.data.data || []
					resolve(data)
				})
			})
		},
		GetREVIEWNUM({
			commit
		}) {
			return new Promise(resolve => {
				ReviewedGoodsNum().then(res1 => {
					commit('SET_REVIEWNUM', res1.data.data)
					resolve(res1.data.data)
				});
			})
		},
		GetADVERTNUM({
						 commit
					 }) {
			return new Promise(resolve => {
				auditAdvertNumber().then(res1 => {
					commit('SET_ADVERTNUM', res1.data.data)
					console.log('res.data.data1',res1.data.data)
					resolve(res1.data.data)
				});
			})
		},
		//获取系统菜单
		GetMenu({
			commit
		}, parentId) {
			return new Promise(resolve => {
				getMenu(parentId).then((res) => {
					const data = (res.data.data[0] || {}).subMenus
					let menu = deepClone(data) || [];
					menu.forEach(ele => {
						addPath(ele, true);
						if (ele.name == "商品管理") {
							ele.children.forEach(obj => {
								if (obj.name == "待审核") {
									ReviewedGoodsNum().then(res1 => {
										commit('SET_REVIEWNUM', res1.data.data)
									});
								}
							})
						} else if (ele.name == "商城管理") {
							ele.children.forEach(obj => {
								if (obj.name == "广告审核") {
									auditAdvertNumber().then(res1 => {
										commit('SET_ADVERTNUM', res1.data.data)
									});
								}
							})
						}
					})
					commit('SET_MENU', menu)
					resolve(menu)
				})
			})
		},
	},
	mutations: {
		OPEN_LOCK: (state) => {
			state.tokenLock = true;
		},
		CLEAR_LOCK: (state) => {
			state.tokenLock = false;
		},
		SET_REVIEWNUM: (state,reviewNum) => {
			state.reviewNum = reviewNum;
		},
		SET_ADVERTNUM: (state,advertNum) => {
			state.advertNum = advertNum;
		},
		SET_TOKEN: (state, token) => {
			state.token = token;
			setToken(state.token) //给sessionStorage中添加token
		},
		SET_USERIFNO: (state, userInfo) => {
			state.userInfo = userInfo;
		},
		SET_MENU: (state, menu) => {
			state.menu = menu
			setStore({
				name: 'menu',
				content: state.menu,
				type: 'session'
			})
		},
		SET_MENU_ALL: (state, menuAll) => {
			state.menuAll = menuAll;
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles;
		},
		SET_PERMISSION: (state, permission) => {
			state.permission = {};
			permission.forEach(ele => {
				// const key = ele.replace('/', '').replace('/', '_')
				const key = ele;
				state.permission[key] = true;
			});
		}
	}

}
export default user
